from django.db import models
from django.contrib import auth
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, UserManager
import re


class BlogUserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_author', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_author', False)  # 默认不是作者
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

    def with_perm(self, perm, is_active=True, include_superusers=True, backend=None, obj=None):
        # the same as UserManager
        if backend is None:
            backends = auth._get_backends(return_tuples=True)
            if len(backends) == 1:
                backend, _ = backends[0]
            else:
                raise ValueError(
                    'You have multiple authentication backends configured and '
                    'therefore must provide the `backend` argument.'
                )
        elif not isinstance(backend, str):
            raise TypeError(
                'backend must be a dotted import path string (got %r).'
                % backend
            )
        else:
            backend = auth.load_backend(backend)
        if hasattr(backend, 'with_perm'):
            return backend.with_perm(
                perm,
                is_active=is_active,
                include_superusers=include_superusers,
                obj=obj,
            )
        return self.none()


class BlogUser(AbstractBaseUser, PermissionsMixin):
    nickname = models.CharField(max_length=30, verbose_name="昵称", default="anonymous user",
                                help_text="最多30个字符")
    email = models.EmailField(unique=True, max_length=255, verbose_name="用户邮箱",
                              help_text="用户唯一标示")
    # TODO 限制头像大小
    avatar = models.ImageField(upload_to='avatar/', verbose_name="头像", null=True, blank=True)
    sex = models.SmallIntegerField(choices=[(0, '男'), (1, '女'), (2, '保密')], default=2, verbose_name="性别")

    is_active = models.BooleanField(default=True)  # 是否活跃
    is_author = models.BooleanField(default=False)  # 作者，有发文章的权利
    date_joined = models.DateTimeField(auto_now_add=True, verbose_name="注册时间")
    # last_login is default for AbstractBaseUser
    last_active_ip = models.GenericIPAddressField(verbose_name="上次登陆IP", null=True, blank=True, editable=False)

    objects = BlogUserManager()

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = 'User'
        verbose_name_plural = 'Users'

    @property
    def is_staff(self):
        return self.is_author or self.is_superuser

    def __str__(self):
        if self.nickname:
            return self.nickname
        else:
            return self.email

    def has_perm(self, perm, obj=None):
        """
        作者只能够修改自己的文章信息
        """
        if self.is_author:
            reg = r'^(?P<app_label>\w+)\.(?P<permission>\w+?)_(?P<codename>\w+)$'
            res = re.search(reg, perm)
            app_label = res['app_label']
            codename = res['codename']
            if obj:
                return app_label == 'blog' and codename == 'blog' and obj.author == self
            else:
                return app_label == 'blog' and codename == 'blog'
        else:
            return super().has_perm(perm, obj)

    def has_module_perms(self, app_label):
        if self.is_author:
            return app_label == 'blog'
        else:
            return super().has_module_perms(app_label)
